<?php

// 兼容 webman：日志用 support\Log，app_path 辅助函数自定义
namespace app\hooks;

use support\Log;

if (!function_exists('app_path')) {
    function app_path($path = '') {
        return base_path('app' . ($path ? DIRECTORY_SEPARATOR . $path : $path));
    }
}

class HookManager
{
    protected $region;
    protected $key;
    protected $normalService = null;
    protected $service = null;
    protected $params;

    /**
     * @param int|string $region
     * @param string $key
     * @param array $params
     * @param bool $isNormal
     */
    public function __construct($region, string $key, array $params, bool $isNormal = true)
    {
        $this->region = $region;
        $this->key = $key;
        $this->params = $params;

        Log::info('HookManager', [$region, $key, $params, $isNormal]);

        $key = ucfirst($key);
        if ($isNormal){
            $this->getNormalService($key);
        }
        $this->getService($key);
    }

    protected function getNormalService(string $key)
    {
        $serviceClass = sprintf("\\app\\hooks\\%s\\HookNormalService", ucfirst($key));
        $this->loadService($serviceClass, $key,  'normalService');
        Log::info('HookManager loadService', [$serviceClass, $key]);
    }

    protected function loadService(string $serviceClass, string $key, string $serviceName)
    {
        $file = app_path("hooks/{$key}/" . basename(str_replace('\\', '/', $serviceClass)) . ".php");
        Log::info('HookManager loadService filePath', [$file]);
        // 检查类文件是否存在
        if (file_exists($file)) {
            if (class_exists($serviceClass) && method_exists($serviceClass, 'handle')) {
                $this->{$serviceName} = new $serviceClass;
            }
        }
    }

    protected function getService(string $key)
    {
        // region 可选，若无 region 则为 HookService
        if ($this->region !== null && $this->region !== '') {
            $serviceClass = sprintf("\\app\\hooks\\%s\\Hook%sService", ucfirst($key), ucfirst($this->region));
        } else {
            $serviceClass = sprintf("\\app\\hooks\\%s\\HookService", ucfirst($key));
        }
        $this->loadService($serviceClass, $key,  'service');
        Log::info('HookManager loadService', [$serviceClass, $key]);
    }

    public function executeHooks()
    {
        if ($this->normalService){
            $this->normalService->handle($this->region, $this->params);
        }

        if ($this->service) {
            $this->service->handle($this->region, $this->params);
        }
    }
}
